package com.niiwoo.civet.trade.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.constant.MqConstant;
import com.niiwoo.civet.trade.dto.request.loan.ProjectWaitPublishReqDTO;
import com.niiwoo.civet.trade.service.local.project.ProjectLocalService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 标的待发布监听器
 *
 * @author TomXue
 * @since 2018-08-13
 */
@Component
@Slf4j
public class ProjectWaitPublishListener {
    @Autowired
    private ProjectLocalService projectLocalService;

    @RabbitListener(queues = {MqConstant.PROJECT_WAIT_PUBLISH_QUEUE})
    public void projectWaitPublishHandler(ProjectWaitPublishReqDTO projectWaitPublishReqDTO, Message message, Channel channel) throws IOException {
        try {
            log.info("标的待发布通知,标的ID={},请求参数={}", projectWaitPublishReqDTO == null ? null : projectWaitPublishReqDTO.getProjectId(), JSON.toJSONString(projectWaitPublishReqDTO));
            projectLocalService.projectWaitPublish(projectWaitPublishReqDTO);
        } catch (Exception e) {
            log.error("标的待发布通知,标的ID={},发生系统异常,原因={}", projectWaitPublishReqDTO == null ? null : projectWaitPublishReqDTO.getProjectId(), e);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
